package com.keda.springdata_elasticsearch.service.impl;

import com.alibaba.fastjson.JSON;
import com.keda.springdata_elasticsearch.entity.ProductDocument;
import com.keda.springdata_elasticsearch.repositories.ProductRepository;
import com.keda.springdata_elasticsearch.service.ProductService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
 * @Description:
 * @Auther: liuyanhui
 * @Date: 2023/01/19/ 14:52
 */
@Service
public class ProductServiceImpl extends BaseSearchServiceImpl<ProductDocument> implements ProductService {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Resource
    private ElasticsearchRestTemplate elasticsearchTemplate;

    @Resource
    private ProductRepository productRepository;

    @Override
    public void save(ProductDocument... productDocuments) {
        IndexOperations indexOperations = elasticsearchTemplate.indexOps(ProductDocument.class);
        indexOperations.putMapping(indexOperations.createMapping());
        if (productDocuments.length > 0) {
            logger.info("【保存索引】：{}", JSON.toJSONString(productRepository.saveAll(Arrays.asList(productDocuments))));
        }
    }

    @Override
    public void delete(String id) {
        productRepository.deleteById(id);
    }

    @Override
    public void deleteAll() {
        productRepository.deleteAll();
    }

    @Override
    public ProductDocument getById(String id) {
        Optional<ProductDocument> byId = productRepository.findById(id);
        if (byId.isPresent()) {
            return byId.get();
        }
        return null;
    }

    @Override
    public List<ProductDocument> getAll() {
        List<ProductDocument> list = new ArrayList<>();
        productRepository.findAll().forEach(list::add);
        return list;
    }
}
